package com.yunxitest.yunxitest.item.wifi;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import com.yunxitest.yunxitest.Interface.IDetectItem;
import com.yunxitest.yunxitest.Interface.IResultCallback;
import com.yunxitest.yunxitest.utils.Constants;
import com.yunxitest.yunxitest.utils.L;
import com.yunxitest.yunxitest.utils.ShellUtils;

import java.util.List;

public class WifiDetectManager implements IDetectItem {
    private Context mContext;
    private IResultCallback callback;
    private WifiManager wifiManager;
    public WifiDetectManager(Context context, IResultCallback callback) {
        mContext = context;
        this.callback = callback;
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    }
//    Timer timer;
//    TimerTask task;

    @Override
    public void startDetect() {
        closeWifi();
        openWifi();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                connectWifi(Constants.INSTANCE.getWIFI_SSID(), Constants.INSTANCE.getWIFI_PASSWORD(), Constants.INSTANCE.getWIFI_TYPE());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean result = isWifiConnect();
                if (result) {
                    if(callback!=null) {
                        callback.success();
                        callback=null;
                    }
                    L.d("testItem", "connect successful .");
                } else {
                    if(callback!=null) {
                        callback.fail("connect time out .");
                        callback=null;
                    }
                }
            }
        }).start();

    }

    @Override
    public void finish() {
        closeWifi();
        ShellUtils.execCmd("echo 0 > /sys/class/gpios-ctrl/usb_ctrl", false);
    }

    private void connectWifi(String targetSsid, String targetPsd, String enc) {
        // 1、注意热点和密码均包含引号，此处需要需要转义引号
        String ssid = "\"" + targetSsid + "\"";
        String psd = "\"" + targetPsd + "\"";

        //2、配置wifi信息
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = ssid;
        switch (enc) {
            case "WEP":
                // 加密类型为WEP
                conf.wepKeys[0] = psd;
                conf.wepTxKeyIndex = 0;
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;
            case "WPA":
                // 加密类型为WPA
                conf.preSharedKey = psd;
                break;
            case "OPEN":
                //开放网络
                conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        //3、链接wifi
        wifiManager.addNetwork(conf);
        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        boolean isFound = false;
        if (list == null) {
            callback.fail("wifi device list is null");
            callback=null;
            return;
        }
        for (WifiConfiguration i : list) {
            if (i.SSID != null && i.SSID.equals(ssid)) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                isFound = true;
                L.d("testItem", " connect wifi @ " + i.SSID + " # pwd  " + psd);
                break;
            }
        }

        if (!isFound) {
            if(callback!=null) {
                callback.fail("not found wifi");
                callback = null;
            }
            L.d("testItem", "not found wifi");
            return;
        }


//        Timer timer = new Timer();
//        TimerTask task = new TimerTask() {
//            int count = 0;
//
//            @Override
//            public void run() {
//                boolean result = isWifiConnect();
//                if (result) {
//                    callback.success();
//                    L.d("testItem", "connect successful .");
//                    this.cancel();
//                } else {
//                    if (count <= 10) {
//                        count++;
//                    } else {
//                        callback.fail("connect time out .");
//                        L.d("testItem", "connect time out .");
//                        this.cancel();
//                    }
//                }
//            }
//        };
//        timer.schedule(task, 0, 2000);
    }


    // 打开WIFI
    private boolean openWifi() {
        boolean bRet = true;
        if (!wifiManager.isWifiEnabled()) {
            bRet = wifiManager.setWifiEnabled(true);
        }
        return bRet;
    }

    // 关闭WIFI
    private void closeWifi() {
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }
    }


    private boolean isWifiConnect() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }

}
